package cn.dglydrpy.study.j2ee.servlet.util;


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 * Cookie工具类  封装Cookie的添加，读取，删除的基本操作
 */
public class CookieUtils {
	
	public static void addCookie(String name,String value,String path,int age,HttpServletResponse response) throws UnsupportedEncodingException{
		Cookie cookie = new Cookie(name,URLEncoder.encode(value, "utf-8"));
		cookie.setMaxAge(age);
		cookie.setPath(path);
		response.addCookie(cookie);
	}
	
	public static void deleteCookie(String name,String path,HttpServletResponse response) throws UnsupportedEncodingException{
		Cookie cookie = new Cookie(URLEncoder.encode(name, "utf-8"),"");
		cookie.setMaxAge(0);
		cookie.setPath(path);
		response.addCookie(cookie);
	}
	
	public static String findCookieByName(String name,HttpServletRequest request) throws UnsupportedEncodingException{
		Cookie[] cookies = request.getCookies();
		if(cookies != null){
			for (Cookie cookie : cookies) {
				if (name.equals(cookie.getName())) {
					return URLDecoder.decode(cookie.getValue(),"utf-8");
				}
			}
		}
		return null;
	}
	
	public static Map<String,String> findCookie(HttpServletRequest request) throws UnsupportedEncodingException{
		Map<String,String> map = new HashMap<String,String>();
		Cookie[] cookies = request.getCookies();
		if(cookies != null){
			for (Cookie cookie : cookies) {
				map.put(URLDecoder.decode(cookie.getName(),"utf-8"),URLDecoder.decode( cookie.getValue(),"utf-8"));
			}
			return map;
		}
		return null;
	}
}
